<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\service\fetch\ocean;

use app\enum\CommonEnum;
use app\enum\ConfigEnum;
use app\enum\OceanEnum;
use app\model\ClientAccountModel;
use app\model\OeAppExtendModel;
use app\model\OeAssetsAppModel;
use app\service\client\AccountService;
use app\service\fetch\MediaInterface;
use app\service\fetch\MediaService;
use app\service\ocean\AdvertiserService;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Model;

class AppExtendService extends MediaService implements MediaInterface
{
    /**
     * @var string 数据拉取key
     */
    protected const FETCH_KEY = ConfigEnum::CACHE_CONFIG[OceanEnum::LIST_CONFIG_LOCK_KEY]['app_extend'];

    /**
     * 获取分包信息.
     *
     * @param string $advertiserId 广告主id
     */
    public static function getAppExtend(string $advertiserId = ''): bool
    {
        try {
            // 获取账户信息
            $obj = AccountService::getAccountModel(0, $advertiserId);
            if (! $obj instanceof ClientAccountModel || ! $obj->getKey()) {
                return self::setError('账户数据不存在');
            }
            $packageIds = self::getPackageList($advertiserId);
            if ($packageIds) {
                foreach ($packageIds as $packageId) {
                    $page = 0;
                    while (true) {
                        $result = self::getList($advertiserId, $packageId, ++$page);
                        if ($result === false) {
                            return false;
                        }
                        if (count($result['data']['list']) == 0) {
                            break;
                        }
                        foreach ($result['data']['list'] as $item) {
                            $model = self::getInfo($advertiserId, $obj->getKey(), $item['package_id'], $item['channel_id'], $packageId);
                            if (! $model instanceof OeAppExtendModel || ! $model->getKey()) {
                                $model = new OeAppExtendModel();
                            }

                            $item['parent_package_id'] = $packageId;
                            $item['account_id'] = $obj->getKey();
                            $item['advertiser_id'] = $advertiserId;
                            $model->setAttrs($item);
                            if (! $model->save()) {
                                throw new \Exception('保存APP分包信息出错');
                            }
                        }
                    }
                }
            }
            return true;
        } catch (\Exception $e) {
            return self::setError($e->getMessage());
        }
    }

    /**
     * 拉取分包信息.
     *
     * @param string $advertiserId 账户id
     * @param string $packageId 包id
     * @param int $page 分页
     * @return bool|mixed|string
     */
    private static function getList(string $advertiserId = '', string $packageId = '', int $page = 1)
    {
        $token = AccountService::getToken(CommonEnum::OE_MEDIA, $advertiserId);
        if (! $token) {
            return self::setError('token获取失败');
        }
        $headers = [
            'Access-Token' => $token,
            'Content-Type' => 'application/json',
        ];
        $params = [
            'advertiser_id' => $advertiserId,
            'package_id' => $packageId,
            'page' => $page,
            'page_size' => OceanEnum::MAX_PAGE_SIZE,
        ];

        return AdvertiserService::getAppExtend($headers, $params);
    }

    /**
     * 获取包列表.
     */
    private static function getPackageList(string $advertiserId = ''): array
    {
        return (new OeAssetsAppModel())->where('advertiser_id', $advertiserId)->column('package_id');
    }

    /**
     * 获取分包信息.
     *
     * @param string $advertiserId 账户id
     * @param int $accountId 账户表id
     * @param string $packageId 分包id
     * @param string $channelId 渠道id
     * @param string $parentPackageId 所属包id
     * @return null|array|mixed|Model|OeAppExtendModel
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private static function getInfo(string $advertiserId = '', int $accountId = 0, string $packageId = '', string $channelId = '', string $parentPackageId = '')
    {
        $where = [
            ['channel_id', '=', $channelId],
            ['package_id', '=', $packageId],
            ['parent_package_id', '=', $parentPackageId],
            ['account_id', '=', $accountId],
            ['advertiser_id', '=', $advertiserId],
        ];

        return (new OeAppExtendModel())->where($where)->field(true)->find();
    }
}
